<template>
  <div>
    <Card>
      <p>昵称： {{ finalUser.nickname }}</p>
      <p>头像:</p>
      <img
        class="myPhoto"
        :src="finalUser.photo"
        @click="$refs['file-inp'].click()"
      />

      <p class="changePhoto" @click="$refs['file-inp'].click()">更换头像</p>

      <input
        hidden
        ref="file-inp"
        type="file"
        accept="image/*"
        @change="inputChange"
      />
      <p style="margin-top: 50px">注：更换头像的裁切器仅供测试使用</p>
      <p>上传裁切后的图片会展示撕裂的图片</p>
      <p>暂时仅支持在线图片测试</p>
    </Card>

    <!-- 头像裁切对话框 -->
    <Modal
      v-model="dialogShow"
      title="更改头像"
      @on-ok="upNewPhoto"
      @on-visible-change="onVisibleChange"
    >
      <div>
        <img class="changeImg" ref="change-img" :src="newSrc" />
      </div>
    </Modal>
  </div>
</template>

<script>
// 头像裁切器
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { mapState } from 'vuex'
// 更新用户头像
import { changeUserPhoto } from '@/api/user'
export default {
  name: 'settingIndex',
  components: {},
  props: {},
  data () {
    return {
      dialogShow: false, // 弹出框展示状态
      newSrc: '', // 需要裁剪的图片
      cropper: null // 裁切器实例
    }
  },
  computed: {
    ...mapState(['finalUser', 'username'])
  },
  watch: {},
  created () { },
  mounted () { },
  methods: {
    // 文本框发生改变时
    inputChange () {
      this.dialogShow = true
      const file = this.$refs['file-inp']
      const blob = window.URL.createObjectURL(file.files[0])
      this.newSrc = blob
    },
    // 显示状态发生变化时触发
    onVisibleChange (val) {
      // 如果为真 就初始化裁切器
      if (val) {
        setTimeout(() => {
          const image = this.$refs['change-img']
          this.cropper = new Cropper(image, {
            aspectRatio: 1 / 1,
            viewMode: 1, // 裁切框不能移出图片范围
            dragMode: 'none' // 背景画布禁止移动
          })
        }, 400)
      } else {
        // 否则就销毁裁切器 清空图片路径
        this.cropper.destroy()
        this.newSrc = ''
      }
    },
    // 点击确定调用接口更换头像
    upNewPhoto () {
      this.cropper.getCroppedCanvas().toBlob(find => {
        changeUserPhoto(
          this.username,
          {
            photo: find
          }
        ).then(res => {
          console.log(res)
        })
      })
    }
  }
}
</script>

<style lang='less' scoped>
.ivu-card {
  width: 600px;
  margin: 20px auto;
  .myPhoto {
    width: 100px;
    height: 100px;
    border-radius: 50%;
  }
}
.changeImg {
  display: block;
  max-width: 100%;
}
.changePhoto {
  cursor: pointer;
  margin-left: 20px;
}
</style>
